#pragma once
// #define BOOST_BEAST_DO_NOT_include_nlohmann_json
#include "const.h"
#include "Singleton.h"
// #include "boost/json.hpp"
// namespace json = boost::json;
#include "json.hpp"
using nlohmann::json;
#include <mutex>
using namespace boost;

class HttpConnection;
typedef std::function<void(std::shared_ptr<HttpConnection>)> HttpHandler;
class LogicSystem : public Singleton<LogicSystem>
{
    friend class Singleton<LogicSystem>;    //不能少，否则基类不能访问构造函数
public:
    //处理Get请求
    bool HandleGetReq(std::string url, std::shared_ptr<HttpConnection> con);
    //处理Post请求
    bool HandlePostReq(std::string url, std::shared_ptr<HttpConnection> con);
    //处理静态资源请求
    // bool HandleStaticReq(std::string url, std::shared_ptr<HttpConnection> con);
private:
    LogicSystem();
    void RegGet(std::string url, HttpHandler handler);  //注册Get请求
    void RegPost(std::string url, HttpHandler handler); //注册Post请求
    std::map<std::string, HttpHandler> _post_handlers;  //post请求处理器
    std::map<std::string, HttpHandler> _get_handlers;   //get请求处理器
    void readJson(const std::string path, json& jv);  //读取解析json文件
    //返回数据通常操作
    void common_rtn_data(std::string message, json& data, std::shared_ptr<HttpConnection> con);
    //返回图片通常操作
    void common_rtn_img(std::string message, char* data, std::size_t len, std::shared_ptr<HttpConnection> con);
    std::size_t deal_img(std::string& img_path, char* data, std::shared_ptr<HttpConnection> con);  //处理图片
    char _buffer[1024];     //图片缓冲
    std::mutex _mtx;    //读取文件互斥量
    std::atomic<bool> _is_panding;   //文件是否读取完毕
    // std::atomic<std::size_t> _written_len;   //已经写入的长度
    void async_read_file(asio::stream_file &file, char *buffer,
                    std::size_t &bytes_read, const std::size_t total_len, std::shared_ptr<HttpConnection> con);
};